<?php
namespace Admin\Model;
use Think\Model;
class NewsModel extends Model{
    public function look(){
        $res = $this->field("id,title,category,remark")->select(); //$this指向的是数据库中和类的名称一致的表

        $headArr=array("主键","标题","分类","简介");
        $this->getExcel($headArr,$res);
    }

    public function getExcel($headArr,$data){
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        vendor("PHPExcel","",".class.php");
        vendor("PHPExcel.IOFactory");

        $date = date("Y_m_d",time());
        $fileName = "news_{$date}.xls";//设置导出文件excel表名称

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel(); //实例化excel的对象


        //设置表头
        $key = ord("A"); //返回 "A" 的 ASCII值：65  B:66 C:67
        //print_r($headArr);exit;
        /* ord() 将字母转化成ascii码
         * chr() 将ascii码转化成字母
         * */
        //设置表头
        foreach($headArr as $v){
            $colum = chr($key); //第一次循环 $key = 65
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
            /*
             * setActiveSheetIndex(0)设置将数据写到excel文件中第一张表
             * setCellValue("单元格"，值) 设置单元格的值
             */
            $key += 1; //第一次循环 $key = 66
        }

        $column = 2;//代表行
        $objActSheet = $objPHPExcel->getActiveSheet();
        //获取是excel文件中哪张表

        foreach($data as $key => $rows){ //行写入
            $span = ord("A"); //65
            foreach($rows as $keyName=>$value){// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j.$column, $value);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);

        //重命名表
        //$objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;

    }
}